package controllers

import (
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"

	"github.com/golang/glog"

	"eccgateway/pkg/config"
	"eccgateway/pkg/util"
)

var iManagerAddress string

type AuthController struct {
}

func (c AuthController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	if len(iManagerAddress) == 0 {
		iManagerAddress = config.GetConfig().String("IManagerAddress")
		glog.Infof("iManagerAddress is %v", iManagerAddress)
	}

	origin, err := url.Parse(iManagerAddress)
	if err != nil {
		glog.Errorf("parse proxy backend address failed, address: %v, err: %v", iManagerAddress, err)
		util.ReturnErrorResponseInResponseWriter(w, http.StatusBadRequest, fmt.Sprintf("parse proxy backend address failed, %v", err))
		return
	}

	glog.Infof("this request will send to address: %v, uri: %v, method: %v", iManagerAddress, r.RequestURI, r.Method)
	director := func(req *http.Request) {
		req.Header.Add(ForwardedHostReqHeader, req.Host)
		req.Header.Add(OriginHostReqHeader, origin.Host)
		req.URL.Scheme = HttpProtocol
		req.URL.Host = origin.Host
		req.URL.Path = r.RequestURI
	}
	proxy := &httputil.ReverseProxy{Director: director}
	proxy.ServeHTTP(w, r)
}
